package org.halo.trade.data.sina;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket(maxTextMessageSize = 4 * 1024 * 1024)
public class SinaWebSocket
{
	private final CountDownLatch closeLatch;
	private Session session;
	private SinaLevel2Fetcher fectcher = null;
	private boolean connected = false;
	private boolean broken = false;

	public boolean isBroken()
	{
		return broken;
	}

	public void setBroken(boolean broken)
	{
		this.broken = broken;
	}

	public boolean isConnected()
	{
		return connected;
	}

	public void setConnected(boolean connected)
	{
		this.connected = connected;
	}

	public SinaWebSocket(SinaLevel2Fetcher fectcher)
	{
		this.closeLatch = new CountDownLatch(1);
		this.fectcher = fectcher;
	}

	public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException
	{
		return this.closeLatch.await(duration, unit);
	}

	@OnWebSocketClose
	public void onClose(int statusCode, String reason)
	{
		System.out.println("SinaWebSocket: onClose."+statusCode+"reason is "+reason);
		this.session = null;
		broken = true;
		this.closeLatch.countDown();
		fectcher.close();
	}

	@OnWebSocketConnect
	public void onConnect(Session session)
	{
		this.session = session;
		connected = true;
		broken = false;
		fectcher.onConnect();
	}

	@OnWebSocketMessage
	public void onMessage(String msg)
	{
		fectcher.parseMessage(msg);
	}

	public void send(String authen_code)
	{
		String msg = "*" + authen_code;
		sendMsg(msg);
	}

	public void sendMsg(String msg)
	{
		Future<Void> fut = session.getRemote().sendStringByFuture(msg);
		System.out.println("fut======"+fut.isDone());
	}

}